package com.kcs.fxmargin.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.bo.OutstandingBO;
import com.kcs.fxmargin.bo.PreSettlementBO;
import com.kcs.fxmargin.bo.ValidateSettlementBO;
import com.kcs.fxmargin.model.TDeals;
import com.kcs.fxmargin.model.TDealsSettle;

public class DealsDao {
	private Logger log = Logger.getLogger(Constant.LOG_FX);

	public List<ValidateSettlementBO> search(Connection conn, PreparedStatement pstm, ResultSet rs, TDeals deals) throws Exception {
		
		List<ValidateSettlementBO> validateSettlementBOList = new ArrayList<ValidateSettlementBO>();
		StringBuffer sql 					= new StringBuffer();
		ValidateSettlementBO	validate 	= null;
				
		sql.append(" SELECT d.cif_no,  ");
		sql.append(" 	c.cust_name, ");
		sql.append(" 	convert(varchar, d.create_dt, 108) input_time, ");
		sql.append(" 	d.deal_id, ");
		sql.append(" 	d.trans_type deal_type, ");
		sql.append(" 	d.outstd_amt amount, ");
		sql.append(" 	d.ccy1 cur, ");
		sql.append(" 	s.settle_amt, ");
		sql.append(" 	s.settle_remain, ");
		sql.append(" 	s.settle_date, ");
		sql.append(" 	s.id deals_settle_id, ");
		sql.append(" 	s.row_version ");
		sql.append(" FROM t_deals d ");
		sql.append(" 	LEFT JOIN t_deals_settle s ON d.deal_id = s.deal_id ");
		sql.append(" 	AND s.active_status = 'A' ");
		sql.append(" 	LEFT JOIN m_cust_info c ON d.cif_no = c.cif_no AND c.active_status = 'A' ");
		sql.append(" WHERE d.active_status = 'A' ");
		sql.append(" AND d.doc_type <> 'CANCEL' ");
		
		if(deals.getValueDate() != null) sql.append(" 	AND d.value_date = ? ");
		if(deals.getCifNo() != null && !"".equals(deals.getCifNo())) sql.append(" 	AND d.cif_no = ? ");
		
		sql.append(" ORDER BY cif_no, ");
		sql.append(" 	input_time ");
		
		log.debug("SQL -> " + sql.toString());
		int index = 1;
		
		pstm = conn.prepareStatement(sql.toString());
		
		if(deals.getValueDate() != null) {
			pstm.setDate(index, deals.getValueDate());
			index++;
		}
		
		if(deals.getCifNo() != null && !"".equals(deals.getCifNo())) {
			pstm.setString(index, deals.getCifNo());
			index++;
		}
		
		rs = pstm.executeQuery();
		index = 1;
		
		while(rs.next()){
			
			validate = new ValidateSettlementBO();
			validate.setIndex(index);
			validate.setCifNo(rs.getString("cif_no"));
			validate.setCustomerName(rs.getString("cust_name"));
			validate.setInputTime(rs.getString("input_time"));
			validate.setDealId(rs.getString("deal_id"));
			validate.setDealType(rs.getString("deal_type"));
			validate.setAmount(rs.getBigDecimal("amount"));
			validate.setCurr(rs.getString("cur"));
			validate.setSettleAmount(rs.getBigDecimal("settle_amt"));
			validate.setSettleRemain(rs.getBigDecimal("settle_remain"));
			validate.setSettleDate((java.util.Date)rs.getDate("settle_date"));
			validate.setDealsSettleId(rs.getString("deals_settle_id"));
			validate.setRowVersion(rs.getInt("row_version"));
			
			validateSettlementBOList.add(validate);
			index++;
		}
		
		log.debug("validateSettlementBOList size = " + validateSettlementBOList.size());
		
		return validateSettlementBOList;
	}
	
	
	public String update(Connection conn, PreparedStatement pstm,TDealsSettle deals) throws Exception {
		
		StringBuffer sql 		= new StringBuffer();
		
		int update = 0;
		
		sql.append(" update t_deals_settle set ");
		sql.append(" settle_amt = ? , ");
		sql.append(" settle_remain = ? , ");
		sql.append(" row_version = ? , ");
		sql.append(" update_by = ? , ");
		sql.append(" update_dt = getDate() ");
		sql.append(" where id = ? ");
		
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setBigDecimal(1, deals.getSettleAmount());
		pstm.setBigDecimal(2, deals.getSettleRemain());
		pstm.setInt(3, deals.getRowVersion());
		pstm.setString(4, deals.getUpdateBy());
		pstm.setString(5, deals.getId());
		
		update = pstm.executeUpdate();
		
		log.debug("update = " + update);
		
		return update == 1 ? "s" : "e";
	}
	
	public String insert(Connection conn, PreparedStatement pstm,TDealsSettle deals) throws Exception {
		
		StringBuffer sql 		= new StringBuffer();
		
		int insert = 0;
		
		sql.append(" insert into t_deals_settle (id, deal_id, settle_amt, settle_remain, settle_date, ");
		sql.append(" active_status, create_by, create_dt, update_by, update_dt, row_version) values  ");
		sql.append(" (?, ?, ?, ?, getDate(), ?, ?, getDate(), ?, getDate(), ?) ");
		
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setString(1, deals.getId());
		pstm.setString(2, deals.getDealId());
		pstm.setBigDecimal(3, deals.getSettleAmount());
		pstm.setBigDecimal(4, deals.getSettleRemain());
		pstm.setString(5, "A");
		pstm.setString(6, deals.getCreateby());
		pstm.setString(7, deals.getUpdateBy());
		pstm.setInt(8, 1);
		
		insert = pstm.executeUpdate();
		
		log.debug("insert = " + insert);
		
		return insert == 1 ? "s" : "e";
	}
	
	
	public List<TDeals> getDeals(Connection conn, PreparedStatement pstm, ResultSet rs) throws Exception {
		
		StringBuffer sql 		= new StringBuffer();
		TDeals deals 			= null;
		List<TDeals> dealsList 	= new ArrayList<TDeals>();
		
		sql.append(" select * ");
		sql.append(" from t_deals ");
		sql.append(" where active_status='A' ");
		sql.append(" and value_date = CAST((GETDATE()-1) as DATE) ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		
		rs = pstm.executeQuery();
		
		while(rs.next()){
			deals = new TDeals();
			deals.setId(rs.getString("id"));
			deals.setBuySell(rs.getString("buy_sell"));
			deals.setCcy1(rs.getString("ccy1"));
			deals.setDealId(rs.getString("deal_id"));
			deals.setRowVersion(rs.getInt("row_version"));
			
			dealsList.add(deals);
		}
		
		log.debug("DealsList size = " + dealsList.size());
		
		return dealsList;
	}
	
	public TDealsSettle getDealsSettle(Connection conn, PreparedStatement pstm, ResultSet rs, String dealId) throws Exception {
		StringBuffer sql 			= new StringBuffer();
		TDealsSettle dealsSettle	= null;
		
		sql.append(" select * ");
		sql.append(" from t_deals_settle ");
		sql.append(" where active_status='A' ");
		sql.append(" and deal_id = ?  ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setString(1, dealId);
		
		rs = pstm.executeQuery();
		
		while(rs.next()){
			dealsSettle = new TDealsSettle();
			dealsSettle.setId(rs.getString("id"));
		}
		
		
		return dealsSettle;
	}
	
	
	public void updateDeals(Connection conn, PreparedStatement pstm, TDeals deals) throws Exception {
		StringBuffer sql = new StringBuffer();
		int update = 0;
		
		sql.append(" update t_deals set ");
		sql.append(" deal_status = ? , ");
		sql.append(" row_version = ? , ");
		sql.append(" update_by = ? , ");
		sql.append(" update_dt = getDate() ");
		sql.append(" where id = ? ");
		
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setString(1, deals.getDealStatus());
		pstm.setInt(2, deals.getRowVersion());
		pstm.setString(3, deals.getUpdateBy());
		pstm.setString(4, deals.getId());
		
		update = pstm.executeUpdate();
		
		log.debug("update = " + update);
	}
	
	public void insertDealsSettle(Connection conn, PreparedStatement pstm, TDealsSettle dealsSettle) throws Exception {
		
		StringBuffer sql = new StringBuffer();
		int insert = 0;
		
		sql.append(" insert into t_deals_settle ");
		sql.append(" (id, deal_id, settle_amt, settle_remain, active_status, ");
		sql.append(" create_by, create_dt, update_by, update_dt, row_version) ");
		sql.append(" values (?, ?, ?, ?, ?, ?, getDate(), ?, getDate(), ?) ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setString(1, dealsSettle.getId());
		pstm.setString(2, dealsSettle.getDealId());
		pstm.setBigDecimal(3, dealsSettle.getSettleAmount());
		pstm.setBigDecimal(4, dealsSettle.getSettleRemain());
		pstm.setString(5, dealsSettle.getActiveStatus());
		pstm.setString(6, dealsSettle.getCreateby());
		pstm.setString(7, dealsSettle.getUpdateBy());
		pstm.setInt(8, dealsSettle.getRowVersion());
		
		insert = pstm.executeUpdate();
		
		log.debug("insert = " + insert);

	}

	public void updateDealsSettle(Connection conn, PreparedStatement pstm, TDealsSettle dealsSettle) throws Exception {
		
		StringBuffer sql = new StringBuffer();
		int update = 0;
		
		sql.append(" update t_deals_settle set ");
		sql.append(" 	settle_amt 		= ? , ");
		sql.append(" 	settle_remain 	= ? , ");
		sql.append(" 	update_by 		= ? , ");
		sql.append(" 	update_dt 		= getDate() , ");
		sql.append(" 	row_version 	= ? ");
		sql.append(" where id = ? ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setBigDecimal(1, dealsSettle.getSettleAmount());
		pstm.setBigDecimal(2, dealsSettle.getSettleRemain());
		pstm.setString(3, dealsSettle.getUpdateBy());
		pstm.setInt(4, dealsSettle.getRowVersion());
		pstm.setString(5, dealsSettle.getId());
		
		update = pstm.executeUpdate();
		
		log.debug("update = " + update);
	
	}
	
	public List<PreSettlementBO> searchPreSettlement(Connection conn, PreparedStatement pstm, ResultSet rs) throws Exception {
		StringBuffer sql 	= new StringBuffer();
		List<PreSettlementBO> preSettleBoList = new ArrayList<PreSettlementBO>();
		PreSettlementBO bo 	= null;
		
		sql.append(" WITH tmp AS ");
		sql.append("   ( SELECT s.cif_no, ");
		sql.append("            max(s.as_of_date) as_of_date ");
		sql.append("    FROM t_deals_sum s ");
		sql.append("    WHERE s.active_status='A' ");
		sql.append("    GROUP BY s.cif_no) , ");
		sql.append("      risks AS ");
		sql.append("   ( SELECT deal_id, trans_date, value_date, ");
		sql.append("      (SELECT isnull( ");
		sql.append("                       (SELECT top 1 risk ");
		sql.append("                        FROM t_ccf ");
		sql.append("                        WHERE active_status='A' ");
		sql.append("                          AND day_count <= DATEDIFF(DAY, trans_date, value_date) ");
		sql.append("                        ORDER BY day_count DESC), 0 )/100) risk ");
		sql.append("    FROM t_deals d ");
		sql.append("    WHERE d.active_status='A') ");
		sql.append(" SELECT d.trans_type type_of_deal, ");
		sql.append("        c.cust_name counterparty , ");
		sql.append("        d.deal_id , ");
		sql.append(" 		d.instrument , ");
		sql.append(" 		d.branch , ");
		sql.append(" 		d.comments , ");
		sql.append(" DATEDIFF(DAY, d.trans_date, d.value_date) maturity, ");
		sql.append(" d.value_date mat_date, ");
		sql.append(" d.buy_sell , ");
		sql.append(" CASE d.buy_sell ");
		sql.append(" WHEN 'B' THEN d.deal_amt1 ");
		sql.append(" WHEN 'S' THEN d.equity_amt ");
		sql.append(" END notional , ");
		sql.append(" CASE d.buy_sell ");
		sql.append(" WHEN 'B' THEN d.ccy1 ");
		sql.append(" WHEN 'S' THEN d.ccy2 ");
		sql.append(" END curr , ");
		sql.append(" risks.risk ");
		sql.append(" , (d.mtm_rate*d.deal_amt1) mkt_value, dsum.cash_bal, d.im_required ,  ");
		sql.append(" (dsum.cash_bal - d.im_required) deduct_margin , ");
		sql.append(" d.pre_settle_used pre_settle_risk ");
		sql.append(" FROM t_deals d ");
		sql.append(" LEFT JOIN m_cust_info c ON d.cif_no = c.cif_no ");
		sql.append(" LEFT JOIN ");
		sql.append("   ( SELECT s.cif_no, ");
		sql.append("            s.cash_bal, ");
		sql.append("            s.pre_settle_risk, ");
		sql.append("            s.pre_settle_used, ");
		sql.append("            s.notional_limit, ");
		sql.append("            s.notional_used ");
		sql.append("    FROM t_deals_sum s, ");
		sql.append("         tmp ");
		sql.append("    WHERE s.active_status='A' ");
		sql.append("      AND s.as_of_date = tmp.as_of_date ");
		sql.append("      AND s.cif_no = tmp.cif_no) dsum ON d.cif_no=dsum.cif_no ");	
		sql.append(" LEFT JOIN risks ON d.deal_id=risks.deal_id ");
		sql.append(" WHERE d.active_status='A' ");
		sql.append(" ORDER BY deal_id ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		
		rs   = pstm.executeQuery();
		int rowNum = 1;
		
		while(rs.next()){
			bo = new PreSettlementBO();
			
			bo.setRowNum(rowNum);
			bo.setTypeOfDeal(rs.getString("type_of_deal"));
			bo.setCounterParty(rs.getString("counterparty"));
			bo.setDealId(rs.getString("deal_id"));
			bo.setInstrument(rs.getString("instrument"));
			bo.setBranceCode(rs.getString("branch"));
			bo.setComments(rs.getString("comments"));
			bo.setMaturity(rs.getString("maturity"));
			bo.setMatdate(rs.getDate("mat_date"));
			bo.setBuySell(rs.getString("buy_sell"));
			bo.setNotional(rs.getBigDecimal("notional"));
			bo.setCurr(rs.getString("curr"));
			bo.setRisk(rs.getBigDecimal("risk"));
			bo.setMktValue(rs.getBigDecimal("mkt_value"));
			bo.setCashBal(rs.getBigDecimal("cash_bal"));
			bo.setImRequired(rs.getBigDecimal("im_required"));
			bo.setDeductMargin(rs.getBigDecimal("deduct_margin"));
			bo.setPreSettleRisk(rs.getBigDecimal("pre_settle_risk"));
			bo.setAddOn();
			
			preSettleBoList.add(bo);
			rowNum++;
		}
		
		log.debug("preSettleBoList size = " + preSettleBoList.size());
		
		return preSettleBoList;
	}
	
	public List<OutstandingBO> searchOutstanding(Connection conn, PreparedStatement pstm, ResultSet rs, OutstandingBO input) throws Exception {
		StringBuffer sql 	= new StringBuffer();
		List<OutstandingBO> outStandingBOList = new ArrayList<OutstandingBO>();
		OutstandingBO bo 	= null;
		
		sql.append(" SELECT h.value_date, ");
		sql.append("        h.deal_id, ");
		sql.append("        c.cust_name, ");
		sql.append("        h.trans_date, ");
		sql.append("        h.exch_rate, ");
		sql.append("        h.mtm_rate , ");
		sql.append("        CASE h.buy_sell ");
		sql.append("            WHEN 'B' THEN h.ccy1 ");
		sql.append("            WHEN 'S' THEN h.ccy2 ");
		sql.append("        END ccy_buy , ");
		sql.append("        CASE h.buy_sell ");
		sql.append("            WHEN 'B' THEN h.deal_amt1 ");
		sql.append("            WHEN 'S' THEN h.equity_amt ");
		sql.append("        END amt_buy , ");
		sql.append("        CASE h.buy_sell ");
		sql.append("            WHEN 'S' THEN h.ccy1 ");
		sql.append("            WHEN 'B' THEN h.ccy2 ");
		sql.append("        END ccy_sell , ");
		sql.append("        CASE h.buy_sell ");
		sql.append("            WHEN 'S' THEN h.deal_amt1 ");
		sql.append("            WHEN 'B' THEN h.equity_amt ");
		sql.append("        END amt_sell ");
		sql.append(" FROM t_deals_history h ");
		sql.append(" LEFT JOIN m_cust_info c ON h.cif_no=c.cif_no ");
		sql.append(" WHERE h.active_status='A' ");
		sql.append("   AND h.as_of_date=h.value_date ");
		sql.append("   AND h.as_of_date BETWEEN ? AND ? ");
		sql.append(" ORDER BY h.value_date, ");
		sql.append("          h.deal_id ");
		
		log.debug("SQL -> " + sql.toString());
		
		pstm = conn.prepareStatement(sql.toString());
		pstm.setDate(1, commonUtils.convertUtilDatetoSQLDate(input.getStartDate()));
		pstm.setDate(2, commonUtils.convertUtilDatetoSQLDate(input.getEndDate()));
		
		rs   = pstm.executeQuery();
		int rowNum = 1;
		
		while(rs.next()){
			bo = new OutstandingBO();
			
			bo.setRowNum(rowNum);
			bo.setExpiryDate(rs.getDate("value_date"));
			bo.setDealId(rs.getString("deal_id"));
			bo.setCustomer(rs.getString("cust_name"));
			bo.setDealDate(rs.getDate("trans_date"));
			bo.setBaseRate(rs.getBigDecimal("exch_rate"));
			bo.setAllInRate(rs.getBigDecimal("mtm_rate"));
			bo.setCcyBuy(rs.getString("ccy_buy"));
			bo.setBuyAmount(rs.getBigDecimal("amt_buy"));
			bo.setCcySell(rs.getString("ccy_sell"));
			bo.setSellAmount(rs.getBigDecimal("amt_sell"));
			
			outStandingBOList.add(bo);
			rowNum++;
		}
		
		log.debug("outStandingBOList size = " + outStandingBOList.size());
		
		return outStandingBOList;
	}
}
